package com.firmye.codereposboot.service;

import com.firmye.codereposboot.dao.BTableDao;
import com.firmye.codereposboot.model.commons.BTResponse;
import com.firmye.codereposboot.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BTableService {

    @Autowired
    private BTableDao bTableDao;

    public BTResponse getData(HttpServletRequest request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Map<String,String> map = new HashMap();

        Enumeration<?> enu = request.getParameterNames();
        log.debug("=====> " + enu.hasMoreElements());
        while(enu.hasMoreElements()){
            String paraName = (String)enu.nextElement();
            log.debug("=====> " + paraName + ":" + request.getParameter(paraName));

            if("sort".equals(paraName)){
                map.put(paraName, StringUtil.toMapper(request.getParameter(paraName)));
            }else{
                map.put(paraName, request.getParameter(paraName));
            }
        }

        Class<? extends Object> clazz = bTableDao.getClass();
        Method getList = clazz.getMethod(map.get("sqlName"), Map.class);
        Method getTotal = clazz.getMethod(map.get("sqlName") + "Total", Map.class);

        List list = (List) getList.invoke(bTableDao, map);
        Integer total = (Integer) getTotal.invoke(bTableDao, map);

        BTResponse btr = new BTResponse();
        btr.setRows(list);
        btr.setTotal(total);

        return btr;
    }


}
